package cn.xopencode.recordservice.service.kvoperation;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.xopencode.common.framework.exception.util.ServiceExceptionUtil;
import cn.xopencode.common.framework.util.DateUtil;
import cn.xopencode.common.framework.util.StringUtils;
import cn.xopencode.common.framework.vo.PageResult;
import cn.xopencode.recordservice.convert.kvoperation.KvOperationRecordConvert;
import cn.xopencode.recordservice.convert.robotroom.AdminRecordConvert;
import cn.xopencode.recordservice.dal.mysql.dataobject.kvoperation.KvOperationRecordDetailDO;
import cn.xopencode.recordservice.dal.mysql.dataobject.kvoperation.KvOperationRecordEmpRelDO;
import cn.xopencode.recordservice.dal.mysql.dataobject.kvoperation.KvOperationRecordOtherDO;
import cn.xopencode.recordservice.dal.mysql.dataobject.pdroom.PowerDistributionRoomDO;
import cn.xopencode.recordservice.dal.mysql.dataobject.sf6machine.Sf6MachineRecordOtherDO;
import cn.xopencode.recordservice.dal.mysql.mapper.kvoperation.KvOperationRecordDetailMapper;
import cn.xopencode.recordservice.dal.mysql.mapper.kvoperation.KvOperationRecordEmplRelMapper;
import cn.xopencode.recordservice.dal.mysql.mapper.kvoperation.KvOperationRecordOtherMapper;
import cn.xopencode.recordservice.dal.mysql.mapper.pdroom.PowerDistributionRoomMapper;
import cn.xopencode.recordservice.rpc.kvoperation.vo.KvOperationRecordAdminPageVO;
import cn.xopencode.recordservice.rpc.kvoperation.vo.KvOperationRecordNextVO;
import cn.xopencode.recordservice.rpc.kvoperation.vo.KvOperationRecordPageVO;
import cn.xopencode.recordservice.rpc.kvoperation.vo.KvOperationRecordVO;
import cn.xopencode.recordservice.service.kvoperation.bo.KvOperationRecordBO;
import cn.xopencode.recordservice.service.kvoperation.bo.KvOperationRecordNextCreateBO;
import cn.xopencode.recordservice.service.kvoperation.bo.KvOperationRecordOtherPageBO;
import cn.xopencode.recordservice.service.robotroom.bo.AdminRecordPageBO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.xopencode.recordservice.enums.RecordErrorCodeConstants.*;

/**
 * 10KV操作室巡检记录 service
 */
@Service
@Validated
public class KvOperationRecordService {

    @Autowired
    private KvOperationRecordEmplRelMapper kvOperationRecordEmplRelMapper;
    @Autowired
    private KvOperationRecordDetailMapper kvOperationRecordDetailMapper;
    @Autowired
    private KvOperationRecordOtherMapper kvOperationRecordOtherMapper;
    @Autowired
    private PowerDistributionRoomMapper powerDistributionRoomMapper;

    public PageResult<KvOperationRecordPageVO> pageKvOperationRecord(KvOperationRecordOtherPageBO pageBO){
        IPage<KvOperationRecordOtherDO> otherDOIPage = kvOperationRecordOtherMapper.selectPage(pageBO);
        PageResult<KvOperationRecordPageVO> pageVo = KvOperationRecordConvert.INSTANCE.convertPage(otherDOIPage);
        List<KvOperationRecordPageVO> list = pageVo.getList();
        if (!CollectionUtil.isEmpty(list)){
            //关联巡检人记录
            for (KvOperationRecordPageVO vo : list) {
                List<KvOperationRecordEmpRelDO> relDoList = kvOperationRecordEmplRelMapper.selectListByRecordCode(vo.getRecordCode());
                List<String> tmp = relDoList.stream().map(KvOperationRecordEmpRelDO::getEmpId).collect(Collectors.toList());
                vo.setEmpRels(String.join(",", tmp));
            }
        }
        return pageVo;
    }

    public String createKvOperationRecord (KvOperationRecordBO recordBO){
        KvOperationRecordOtherDO otherDO = KvOperationRecordConvert.INSTANCE.convert(recordBO);
        KvOperationRecordDetailDO detailDO = KvOperationRecordConvert.INSTANCE.convert2(recordBO);
        String recordCode = IdUtil.objectId();

        //维护kv_operation_record_other 表中的is_notice_leader值
        //业务逻辑：当巡检记录中的detail中的值noticeLeader，有一个为true时，other中的noticeLeader为true
        if (detailDO.getNoticeLeader()) {
            otherDO.setNoticeLeader(true);
        }

        //保存 10KV操作室巡检记录 其余字段
        otherDO.setRecordCode(recordCode);
        otherDO.setId(IdUtil.objectId());
        kvOperationRecordOtherMapper.insert(otherDO);

        //保存关联的巡检人信息
        Set<String> empIds = recordBO.getEmpIds();
        if (!CollectionUtil.isEmpty(empIds)) {
            List<KvOperationRecordEmpRelDO> empRels = empIds.stream()
                    .map(empId -> new KvOperationRecordEmpRelDO().setId(IdUtil.objectId()).setEmpId(empId)
                            .setRecordCode(recordCode)).collect(Collectors.toList());
            kvOperationRecordEmplRelMapper.insertList(empRels);
        }

        //保存 10KV操作室巡检记录明细
        detailDO.setRecordCode(recordCode);
        detailDO.setLeaderDeal(false);
        detailDO.setId(IdUtil.objectId());
        kvOperationRecordDetailMapper.insert(detailDO);

        return recordCode;
    }

    public Integer createKvOperationRecordNextLine(KvOperationRecordNextCreateBO nextCreateBO){
        //下一组保存时需要检查是否重复
        KvOperationRecordDetailDO detailDO = kvOperationRecordDetailMapper.getKvOperationRecordDetailByRecordCodeAndNum(nextCreateBO);
        if(detailDO != null && !StringUtils.isEmpty(detailDO.getId())){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_EXITS);
        }
        KvOperationRecordDetailDO detailDO1 = KvOperationRecordConvert.INSTANCE.convert(nextCreateBO);
        detailDO1.setId(IdUtil.objectId());
        int result = kvOperationRecordDetailMapper.insert(detailDO1);

        //维护kv_operation_record_other 表中的is_notice_leader值
        //业务逻辑：当巡检记录中的detail中的值noticeLeader，有一个为true时，other中的noticeLeader为true
        if(detailDO1.getNoticeLeader()){
            KvOperationRecordOtherDO otherDO = kvOperationRecordOtherMapper.getKvOperationRecordOtherDOByRecordCode(detailDO1.getRecordCode());
            otherDO.setNoticeLeader(true);
            kvOperationRecordOtherMapper.updateById(otherDO);
        }
        return result;
    }

    public Integer updateKvOperationRecord(KvOperationRecordBO recordBO){
        KvOperationRecordOtherDO otherDO = KvOperationRecordConvert.INSTANCE.convert(recordBO);
        KvOperationRecordDetailDO detailDO = KvOperationRecordConvert.INSTANCE.convert2(recordBO);

        String recordCode = recordBO.getRecordCode();
        //维护kv_operation_record_other 表中的is_notice_leader值
        //业务逻辑：当巡检记录的detail中的值noticeLeader，有一个为true时，other中的noticeLeader为true
        if (detailDO.getNoticeLeader()) {
            otherDO.setNoticeLeader(true);
        }else{
            Integer num = kvOperationRecordDetailMapper.selectNeedNoticeLeaderCountByRecordCode(recordCode);
            if(num > 0){
                otherDO.setNoticeLeader(true);
            }else{
                otherDO.setNoticeLeader(false);
            }
        }
        //保存 10KV操作室巡检记录 其余字段
        kvOperationRecordOtherMapper.updateById(otherDO);

        //先删除所有关联的巡检人
        kvOperationRecordEmplRelMapper.deleteByRecordCode(recordCode);

        //保存关联的巡检人信息
        Set<String> empIds = recordBO.getEmpIds();
        if (!CollectionUtil.isEmpty(empIds)) {
            List<KvOperationRecordEmpRelDO> empRels = empIds.stream()
                    .map(empId -> new KvOperationRecordEmpRelDO().setId(IdUtil.objectId()).setEmpId(empId)
                            .setRecordCode(recordCode)).collect(Collectors.toList());
            kvOperationRecordEmplRelMapper.insertList(empRels);
        }

        //保存 10KV操作室巡检记录明细
        detailDO.setId(recordBO.getRecordDetailId());
        return kvOperationRecordDetailMapper.updateById(detailDO);
    }

    public Integer updateKvOperationRecordNextLine(KvOperationRecordNextCreateBO nextCreateBO){
        //下一组保存时需要检查是否重复，校验重复不包含当条数据
        KvOperationRecordDetailDO detailDO = kvOperationRecordDetailMapper.getKvOperationRecordDetailByRecordCodeAndNum(nextCreateBO);
        if(detailDO != null && !detailDO.getId().equals(nextCreateBO.getId()) && !StringUtils.isEmpty(detailDO.getId())){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_EXITS);
        }KvOperationRecordDetailDO detailDO1 = KvOperationRecordConvert.INSTANCE.convert(nextCreateBO);
        int result = kvOperationRecordDetailMapper.updateById(detailDO1);

        //维护kv_operation_record_other 表中的is_notice_leader值
        //业务逻辑：当巡检记录的detail中的值noticeLeader，有一个为true时，other中的noticeLeader为true
        KvOperationRecordOtherDO otherDO = kvOperationRecordOtherMapper.getKvOperationRecordOtherDOByRecordCode(detailDO1.getRecordCode());
        if (detailDO1.getNoticeLeader()) {
            otherDO.setNoticeLeader(true);
        }else{
            Integer num = kvOperationRecordDetailMapper.selectNeedLeaderDealCountByRecordCode(detailDO1.getRecordCode());
            if(num > 0){
                otherDO.setNoticeLeader(true);
            }else{
                otherDO.setNoticeLeader(false);
            }
        }
        kvOperationRecordOtherMapper.updateById(otherDO);
        return result;
    }

    public KvOperationRecordVO getKvOperationRecordById(String recordId){
        KvOperationRecordOtherDO otherDo = kvOperationRecordOtherMapper.selectById(recordId);
        if(otherDo == null){
            throw  ServiceExceptionUtil.exception(RECORD_KVOPERATIONE_QUERY_ERROR);
        }
        KvOperationRecordVO recordVO= KvOperationRecordConvert.INSTANCE.convert(otherDo);

        KvOperationRecordDetailDO detailDO = kvOperationRecordDetailMapper.getFirstKvOperationRecordDetailByRecordCode(otherDo.getRecordCode(), 1);
        recordVO.setPdroomId(detailDO.getPdroomId());
        recordVO.setVoltageA(detailDO.getVoltageA());
        recordVO.setVoltageB(detailDO.getVoltageB());
        recordVO.setVoltageC(detailDO.getVoltageC());
        recordVO.setCurrentA(detailDO.getCurrentA());
        recordVO.setCurrentC(detailDO.getCurrentC());
        recordVO.setRemark(detailDO.getRemark());
        recordVO.setNoticeLeader(detailDO.getNoticeLeader());

        //获取序号和继电器位置（线路名称）
        PowerDistributionRoomDO roomDO = powerDistributionRoomMapper.selectById(detailDO.getPdroomId());
        if(roomDO == null){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_PDROOM_NOT_EXITS2);
        }
        recordVO.setNum(roomDO.getNum());
        recordVO.setLineName(roomDO.getRoomName());

        //巡检位置
        PowerDistributionRoomDO roomDO2 = powerDistributionRoomMapper.selectById(otherDo.getRoomId());
        if(roomDO2 == null){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_PDROOM_NOT_EXITS);
        }
        recordVO.setPdroomName(roomDO2.getRoomName());

        //巡检人
        List<KvOperationRecordEmpRelDO> empRelDOList = kvOperationRecordEmplRelMapper.selectListByRecordCode(otherDo.getRecordCode());
        String empIds = StringUtils.join(empRelDOList.stream().map(KvOperationRecordEmpRelDO::getEmpId).collect(Collectors.toList()),",");
        recordVO.setEmpIds(empIds);
        return recordVO;
    }

    public KvOperationRecordNextVO getKvOperationRecordNextById(String recordCode,Integer recordSeq){
        KvOperationRecordDetailDO detailDO = kvOperationRecordDetailMapper.getFirstKvOperationRecordDetailByRecordCode(recordCode, recordSeq);
        KvOperationRecordNextVO nextVO = KvOperationRecordConvert.INSTANCE.convert(detailDO);

        //获取序号和继电器位置（线路名称）
        PowerDistributionRoomDO roomDO = powerDistributionRoomMapper.selectById(detailDO.getPdroomId());
        nextVO.setNum(roomDO.getNum());
        nextVO.setLineName(roomDO.getRoomName());
        return nextVO;
    }

    public Integer dealKvOperationRecordLineException(String recordDetailId){
        KvOperationRecordDetailDO detailDO = kvOperationRecordDetailMapper.selectById(recordDetailId);
        if(detailDO == null){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_DETAIL_NOT_EXITS);
        }
        if(detailDO != null && detailDO.getNoticeLeader() != true){
            throw ServiceExceptionUtil.exception(RECORD_KVOPERATION_DETAIL_NOT_EXCEPTION);
        }
        detailDO.setLeaderDeal(true);
        int result = kvOperationRecordDetailMapper.updateById(detailDO);

        //维护kv_operation_record_other 表中的is_leader_deal值
        //业务逻辑：当巡检记录的detail中的值leaderDeal，有一个为false时，other中的leaderDeal为false
        KvOperationRecordOtherDO otherDO = kvOperationRecordOtherMapper.getKvOperationRecordOtherDOByRecordCode(detailDO.getRecordCode());
        int num = kvOperationRecordDetailMapper.selectNeedLeaderDealCountByRecordCode(detailDO.getRecordCode());
        if(num <= 0){
            otherDO.setLeaderDeal(true);
        }else{
            otherDO.setLeaderDeal(false);
        }
        kvOperationRecordOtherMapper.updateById(otherDO);
        return result;
    }

    public PageResult<KvOperationRecordAdminPageVO> getAdminPage10KvOperationRecord(AdminRecordPageBO pageBO){
        Page<KvOperationRecordDetailDO> page = new Page<>(pageBO.getPageNo(),pageBO.getPageSize());
        if(pageBO.getInspectionTime() != null){
            String date = DateUtil.format(pageBO.getInspectionTime(), "yyyy-MM-dd");
            pageBO.setInspectionTime1(date.concat(" 00:00:00"));
            pageBO.setInspectionTime2(date.concat(" 23:59:59"));
        }
        IPage<KvOperationRecordOtherDO> detailDOIPage =  kvOperationRecordOtherMapper.adminQuery(page,pageBO);
        return AdminRecordConvert.INSTANCE.convert2(detailDOIPage);
    }

}
